package com.joeyzh.soundrecorder.audio;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.joeyzh.soundrecorder.R;
import com.joeyzh.soundrecorder.bean.AudioModel;
import com.joeyzh.soundrecorder.utils.RecordingListener;

import java.io.File;
import java.io.Serializable;


/**
 * Created by xhl on 2020/12/7
 *
 * @author xhl
 * @Description
 */

public class AudioDialogFragment extends DialogFragment implements RecordingListener {

    public final static int PLAY = 0x1;
    public final static int RECORD = 0x2;
    private static int countdownTime = 60;
    private ImageView mIvClose;
    private AudioView mRecorfView;
    private Button mRerecording;//重录
    private View view1;
    private ImageButton mIvPause;//暂停
    private ImageButton mIvPlay;//录音
    private ImageButton mIvRecord;//播放
    private Button mConfirm;//确定
    //    private Intent mRecordingService;
    private int nowModel = RECORD;
    private MyBroadcastReceiver br;
    private AudioModel mRecordingModel;
    private OnAudioListener onAudioListener;
    //是否为确认点击
    private boolean isConfirm = false;

    public static AudioDialogFragment newInstance(int model) {

        Bundle args = new Bundle();
        args.putInt("nowModel", model);
        AudioDialogFragment fragment = new AudioDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static AudioDialogFragment newInstance() {
        return newInstance(RECORD, countdownTime);
    }

    public static AudioDialogFragment newInstance(int nowModel, int countdownTime) {
        Bundle args = new Bundle();
        args.putInt("nowModel", nowModel);
        args.putInt("countdownTime", countdownTime);
        AudioDialogFragment fragment = new AudioDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static AudioDialogFragment newInstance(int nowModel, int countdownTime, AudioModel recording) {
        Bundle args = new Bundle();
        args.putInt("nowModel", nowModel);
        args.putInt("countdownTime", countdownTime);
        args.putSerializable("recording", (Serializable) recording);
        AudioDialogFragment fragment = new AudioDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public void setOnAudioListener(OnAudioListener onAudioListener) {
        this.onAudioListener = onAudioListener;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        nowModel = getArguments().getInt("nowModel");
        countdownTime = getArguments().getInt("countdownTime");
        if (getArguments().containsKey("recording")) {
            mRecordingModel = (AudioModel) getArguments().getSerializable("recording");
        }
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_record_audio, null);
        initId(view);
        initView();

        builder.setCancelable(false);
        builder.setView(view);
        return builder.create();
    }
    /**
     * Activity创建后才会有window
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().setCanceledOnTouchOutside(false);//调用这个方法时，按对话框以外的地方不起作用。按返回键还起作用。
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//需要这一行来解决对话框背景有白色的问题(颜色随主题变动)
        getDialog().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    private void initId(View root) {
        mIvClose = root.findViewById(R.id.record_audio_iv_close);
        mRecorfView = root.findViewById(R.id.recordView);
        mRerecording = root.findViewById(R.id.btn_rerecording);
        view1 = root.findViewById(R.id.view_1);
        mIvPause = root.findViewById(R.id.ib_pause);
        mIvPlay = root.findViewById(R.id.ib_play);
        mIvRecord = root.findViewById(R.id.ib_record);
        mConfirm = root.findViewById(R.id.btn_confirm);
    }


    private void initView() {
        //注册广播
        br = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("audio");
        //注册广播
        getActivity().registerReceiver(br, filter);
//        mRecordingService = new Intent(getActivity(), RecordingService.class);

        //仅支持播放
        if (PLAY == nowModel) {
            mRecorfView.setModel(AudioView.MODEL_PLAY);
            mRerecording.setVisibility(View.GONE);
            mIvPause.setVisibility(View.GONE);
            mConfirm.setVisibility(View.GONE);
            mIvRecord.setVisibility(View.GONE);
            //显示播放键
            mIvPlay.setVisibility(View.VISIBLE);
        } else {
            mRecorfView.setModel(AudioView.MODEL_RECORD);
            mRerecording.setVisibility(View.GONE);
            mIvPlay.setVisibility(View.GONE);
            mIvPause.setVisibility(View.GONE);
            mIvRecord.setVisibility(View.VISIBLE);
            mConfirm.setVisibility(View.GONE);
        }


        //语音监听
        mRecorfView.setRecordingListener(this);
        if (null != mRecordingModel && !mRecordingModel.getFileName().isEmpty()) {
            mRecorfView.setCountdownTime(mRecordingModel.getElpasedInt());
        } else {
            mRecorfView.setCountdownTime(countdownTime);
        }

//        mRecorfView.setOnCountDownListener(new AudioView.OnCountDownListener() {
//            @Override
//            public void onCountDown() {
////                mRecorfView.stop();
////                Toast.makeText(getActivity(), "计时结束啦~~", Toast.LENGTH_SHORT).show();
//            }
//        });
        mIvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除语音文件
                if (RECORD == nowModel && null != mRecordingModel && null != mRecordingModel.getFile()) {
                    AudioModel.clearRecordingDirectory(mRecordingModel.getFile());
                }
                dismiss();
            }
        });
        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isConfirm = true;
                if (null != onAudioListener) {
                    if (PLAY == nowModel) {
                        onAudioListener.onAudioFile(null);
                        return;
                    }
                    onAudioListener.onAudioFile(mRecordingModel);
                }
                dismiss();

            }
        });
        mRerecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecorfView.setRecordingModel(null);
                //重录时间重新设置
                mRecorfView.setCountdownTime(countdownTime);
                //如果为播放时，则切换到录音模式
                if (mRecorfView.getModel() == AudioView.MODEL_PLAY) {
                    mRecorfView.setModel(AudioView.MODEL_RECORD);
                }
                //重录时先清空文件
                if (null != mRecordingModel && null != mRecordingModel.getFile()) {
                    AudioModel.clearRecordingDirectory(mRecordingModel.getFile());
                }
//                mRecordingModel = null;
                //并且进行录音
                onRecord(true);
            }
        });
        mIvPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecorfView.setRecordingModel(mRecordingModel);
                onRecord(true);
            }
        });
        mIvPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRecord(false);
            }
        });
        mIvRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRecord(true);
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //播放机制时，对文件操作
        if (RECORD == nowModel) {
            if (!isConfirm && null != mRecordingModel && !mRecordingModel.getFilePath().isEmpty()) {
                //页面其他地方退出时。则清空之前录制音频
                AudioModel.clearRecordingDirectory(new File(mRecordingModel.getFilePath()));
            }
        }
        if (null != br) {
            //注销广播
            getActivity().unregisterReceiver(br);
        }
        //进度未开始。不用关闭
        if (mRecorfView.getProgress() <= 0) {
            return;
        }
        //进度开始后关闭机制即可
        mRecorfView.stopRecord();
    }

    private void onRecord(boolean start) {
        if (start) {
//            Toast.makeText(getActivity(), "开始录音...", Toast.LENGTH_SHORT).show();
            //开始
            mRecorfView.start();
        } else {
            mRecorfView.cancel();
//            Toast.makeText(getActivity(), "录音结束...", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRecordingStart() {
        File folder = new File(Environment.getExternalStorageDirectory() + "/SoundRecorder");
        if (!folder.exists()) {
            folder.mkdir();
        }
        //是否为播放
//        boolean isPlay = false;
//        //播放器为播放模式时
//        if (mRecorfView.getModel() == AudioView.MODEL_PLAY) {
//            isPlay = true;
//        }
//        mRecordingService.putExtra("play", isPlay);
//        mRecordingService.putExtra("recording", (Serializable) mRecordingModel);
//        getActivity().startService(mRecordingService);
//        mIvClose.setVisibility(View.INVISIBLE);
        mIvRecord.setVisibility(View.GONE);
        mIvPause.setVisibility(View.VISIBLE);
        mIvPlay.setVisibility(View.GONE);
        mConfirm.setVisibility(View.GONE);
        //隐藏
        setRerecordingVis(View.GONE);

    }

    @Override
    public void onRecordingCancel() {
//        getActivity().stopService(mRecordingService);
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //录音时，点击暂停键则未播放页面
        if (mRecorfView.getModel() == AudioView.MODEL_RECORD) {
            mRecorfView.setModel(AudioView.MODEL_PLAY);
        }

        if (PLAY == nowModel) {
            mConfirm.setVisibility(View.GONE);
            setRerecordingVis(View.GONE);
        } else {
            setRerecordingVis(View.VISIBLE);
            mConfirm.setVisibility(View.VISIBLE);
        }
        mIvPause.setVisibility(View.GONE);
        mIvPlay.setVisibility(View.VISIBLE);
//        mIvClose.setVisibility(View.VISIBLE);
    }

    /**
     * 重录
     *
     * @param vis
     */
    private void setRerecordingVis(int vis) {
        if (vis == mRerecording.getVisibility()) {
            return;
        }
        mRerecording.setVisibility(vis);
//        view1.setVisibility(vis);
    }

    public interface OnAudioListener {
        void onAudioFile(AudioModel recordingModel);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra("isStart", true) || PLAY == nowModel) {
                mRecordingModel = null;
                return;
            }
            //这里的intent可以获取发送广播时传入的数据
            mRecordingModel = (AudioModel) intent.getSerializableExtra("recordingModel");
            //设置时长.用于再次播放时为文件实际时长
            mRecorfView.setCountdownTime(mRecordingModel.getElpasedInt());
            mRecorfView.setRecordingModel(mRecordingModel);
        }
    }
}
